package com.open.launcher.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.open.launcher.R;
import com.open.launcher.base.MyApplication;
import com.open.launcher.base.SysApplication;
import com.open.launcher.bean.HomePageBean;
import com.open.launcher.bean.allchannels.AllChannel;
import com.open.launcher.presenter.HomePagePresenter;
import com.open.launcher.promote.AuthCallBack;
import com.open.launcher.promote.AuthRunnable;
import com.open.launcher.service.HeartServer;
import com.open.launcher.utils.Consts;
import com.open.launcher.utils.Paths;
import com.open.library.utils.PreferencesUtils;
import com.tencent.smtt.sdk.WebSettings;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Launcher 主界面
 *
 * @Author: hailong.qiu
 * @Maintainer: hailong.qiu
 * @Date: 2018.03.26
 * @Copyright: 2018   Inc. All rights reserved.
 */
public class MainActivity extends BaseActivity implements HomePagePresenter.Callback{

    String langStr = "";
    String saveUrl = "";
    private SharedPreferences sharePreference;
//    @BindView(R.id.launcher_webview)
//    WebView launcherWebview;
//    @BindView(R.id.activity_main_bg_iv)
//    ImageView bgIv;
//    @BindView(R.id.main_activity_progress_text)
//    TextView prgress_text;
//    @BindView(R.id.main_activity_progress)
//    TextProgressBar progress;
//    @BindView(R.id.progress_ll)
//    LinearLayout progressll;
    private int progress = 0;
    File apkFile;
    public static  boolean loginFlag = false;
    private HomePagePresenter homePagePresenter;
    private WebSettings webSettings;
    private static final int PROGRESS_NET=1000;
    private static final int PROGRESS_AUTH=1001;
    private static final int PROGRESS_DONE=1002;
    private static final int PROGRESS_NET_SUCCESS=1003;
    private static final int PROGRESS_AUTH_FAILED=1005;
    private static final int PROGRESS_NET_FAILED=1004;
    private static final int HEART_MESSAGE=1006;
    private static final int APK_DOWN_CONPELETE=100;
    private MYCountDownTimer countDownTimer;
    private MyAuthCountDownTimer myAuthCountDownTimer;



    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case APK_DOWN_CONPELETE:
                    if (apkFile!=null&&apkFile.exists()){
//                        install(apkFile);
                        installSilently(apkFile.getAbsolutePath());
                    }
                    break;
                case PROGRESS_NET:
                    Log.i("legend", "handleMessage:     PROGRESS_NET");
//                    prgress_text.setText("正在验证网络是否可用");
                    progress = 50;
                    countDownTimer = new MYCountDownTimer(30000,1000);
                    countDownTimer.start();
                    break;
                case PROGRESS_NET_SUCCESS:
                    countDownTimer.cancel();
                    progress = 80;
                    myAuthCountDownTimer=new MyAuthCountDownTimer(6000,1000);
                    myAuthCountDownTimer.start();
                    if (TextUtils.isEmpty(PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_PORT))){
                        startSettingActivity();
                        return;
                    }

                    Log.i("legend", "handleMessage:     PROGRESS_NET_SUCCESS");
                    authAh(PreferencesUtils.getString(getApplicationContext(), Consts.IP_ROOM_NO_KEY),((LauncherApplication)getApplicationContext()).getManAddr());
                    break;
                case PROGRESS_NET_FAILED:
                    Toast.makeText(MainActivity.this, "网络不可用", Toast.LENGTH_SHORT).show();
                    Log.i("legend", "handleMessage:     PROGRESS_NET_FAILED");
                    startSettingActivity();
                    break;
                case PROGRESS_AUTH:
                    Log.i("legend", "handleMessage:     PROGRESS_AUTH");
                    myAuthCountDownTimer.cancel();
//                    prgress_text.setText("登录成功");
                    progress = 100;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent =new Intent(MainActivity.this, PlayerActivity.class);
                            intent.putExtra("type", 0);
                            startActivity(intent);
                        }
                    },2000);

                    break;
                case PROGRESS_AUTH_FAILED:
                    myAuthCountDownTimer.cancel();
                    Toast.makeText(getApplicationContext(),"服务器异常",Toast.LENGTH_SHORT).show();
                    startSettingActivity();
                    break;
                case HEART_MESSAGE:
                    Intent playIntent = new Intent(getApplicationContext(),HeartServer.class);
                    startService(playIntent);
                    break;

            }
        }
    };
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String ipString = PreferencesUtils.getString(this, Consts.IP_ADDR_KEY);
        Consts.ROOT_ADDRIP = ipString;
        SysApplication.getInstance().addActivity(this);
        try {
            File file = new File(getFilesDir().getAbsolutePath(),"iptv_new.apk");
            if (file!=null&&file.exists()){
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        progress = 20;
        handler.sendEmptyMessageDelayed(PROGRESS_NET,1000);
        sharePreference = getSharedPreferences("user",0);
        editInfo("launcher_ver","0");
        homePagePresenter = new HomePagePresenter(this);

    }
    /**
     * The install command installs a package to the system. Options:
     *
     * @command -l: install the package with FORWARD_LOCK.
     * @command -r: reinstall an existing app, keeping its data.
     * @command -t: allow test .apks to be installed.
     * @command -i: specify the installer package name.
     * @command -s: install package on sdcard.
     * @command -f: install package on internal flash.
     */
    /**
     * The uninstall command removes a package from the system. Options:
     *
     * @command -k: keep the data and cache directories around. after the
     *          package removal.
     */
    private String installSilently(String path) {

        // 通过命令行来安装APK
        String[] args = { "pm", "install", "-r", path };
        String result = "";
        // 创建一个操作系统进程并执行命令行操作
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('\n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
    public boolean isNetworkOnline() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("ping -c 1 -w 1 "+PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_KEY));
            int exitValue = ipProcess.waitFor();
            Log.i("Avalible", "Process:"+exitValue);
            return (exitValue == 0);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
    class MYCountDownTimer extends CountDownTimer{

        public MYCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }
        @Override
        public void onTick(long l) {
//            if (isNetworkOnline()){
            handler.sendEmptyMessage(PROGRESS_NET_SUCCESS);
//            }

        }

        @Override
        public void onFinish() {
            handler.sendEmptyMessage(PROGRESS_NET_FAILED);
        }
    }
    class MyAuthCountDownTimer extends CountDownTimer{

        public MyAuthCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }
        @Override
        public void onTick(long l) {
            if (loginFlag){
                handler.sendEmptyMessage(PROGRESS_AUTH);
            }

        }

        @Override
        public void onFinish() {
            handler.sendEmptyMessage(PROGRESS_AUTH_FAILED);
        }
    }
    private void getAllChannels(){
        OkHttpUtils.get().url("http://"+PreferencesUtils.getString(this, Consts.IP_ADDR_KEY) +":"+PreferencesUtils.getString(this, Consts.IP_ADDR_PORT)+ Paths.CHANNEL_PATH).
                addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + Contast.USE_TOKEN)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("legend", "onError: ");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("legend", "onResponse: "+response);
                MyApplication.allChannel = JSON.parseObject(response,AllChannel.class);
            }
        });
    }
    boolean isFirst = true;

    private void startSettingActivity(){
        isFirst = true;
        Intent i = new Intent(getApplicationContext(), SettingActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (progress==50&&isNetworkOnline()){
            handler.sendEmptyMessage(PROGRESS_NET_SUCCESS);
        }
        if (progress==80){
            String ipString = PreferencesUtils.getString(this, Consts.IP_ADDR_KEY);
            Consts.ROOT_ADDRIP = ipString;
            handler.sendEmptyMessage(PROGRESS_NET_SUCCESS);
        }
    }

    List<Integer> mKeyList = new ArrayList<Integer>() {
        {
            add(KeyEvent.KEYCODE_DPAD_UP);
            add(KeyEvent.KEYCODE_DPAD_UP);
            add(KeyEvent.KEYCODE_DPAD_DOWN);
            add(KeyEvent.KEYCODE_DPAD_DOWN);
            add(KeyEvent.KEYCODE_DPAD_LEFT);
            add(KeyEvent.KEYCODE_DPAD_LEFT);
            add(KeyEvent.KEYCODE_DPAD_RIGHT);
            add(KeyEvent.KEYCODE_DPAD_RIGHT);
            add(-250);
        }
    };

    // 密码解密(弹出系统设置管理员界面): 上上下下左左右右
    int mKeyIndex = 0;
    long oldTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            long time = System.currentTimeMillis();
            if ((time - oldTime) > 2000) {
                mKeyIndex = 0;
            }
            oldTime = time;
            Log.i("legend", "dispatchKeyEvent: setting"+event.getKeyCode());
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_DPAD_UP:
                    if (mKeyList.get(mKeyIndex) == KeyEvent.KEYCODE_DPAD_UP) {
                        mKeyIndex++;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (mKeyList.get(mKeyIndex) == KeyEvent.KEYCODE_DPAD_DOWN) {
                        mKeyIndex++;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    if (mKeyList.get(mKeyIndex) == KeyEvent.KEYCODE_DPAD_RIGHT) {
                        mKeyIndex++;
                    }
                    if (mKeyList.get(mKeyIndex) == -250) {
                        mKeyIndex = 0;
                        isFirst = true;
                        Intent i = new Intent(getApplicationContext(), SettingActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);
//                        startActivity(new Intent(this, SettingActivity.class));
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    if (mKeyList.get(mKeyIndex) == KeyEvent.KEYCODE_DPAD_LEFT) {
                        mKeyIndex++;
                    }
                    break;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
    }

    private void authAh(String useName, String macAdrress){
        AuthRunnable authRunnable = new AuthRunnable();
        authRunnable.setCallBack(new AuthCallBack() {
            @Override
            public void completeUpdateInfo(int code,final String imgUrl, String img_md5, int launcher_ver, final String apk_code, final String apk_url) {
//                handler.sendEmptyMessage(HEART_MESSAGE);
                if (code==200){
                    handler.sendEmptyMessage(PROGRESS_AUTH);
                }else {
                    startSettingActivity();
                }
                homePagePresenter.loadLiveList();
                getAllChannels();
                //更新并下载安装apk
                try {
                    String versionCodeName = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(),0).versionName;
                    if (!versionCodeName.equals(apk_code)&&apk_url!=null&&!TextUtils.isEmpty(apk_url)){
                        Log.i("legend", "completeUpdateInfo: "+getFilesDir().getAbsolutePath() + "iptv_new.apk");
                        loadFile("http://"+PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_KEY)+apk_url,getFilesDir().getAbsolutePath()+"/","iptv_new.apk");
                    }

                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error() {
                Log.i("legend", "error: ");
                startSettingActivity();
            }
        });
        Log.i("legendqi", "auth::  "+"http://"+PreferencesUtils.getString(this, Consts.IP_ADDR_KEY) + ":"+PreferencesUtils.getString(this, Consts.IP_ADDR_PORT) +Paths.AUTH);
        authRunnable.loadData("http://"+PreferencesUtils.getString(this, Consts.IP_ADDR_KEY)+":"+PreferencesUtils.getString(this, Consts.IP_ADDR_PORT) +Paths.AUTH,useName,macAdrress);
    }


    public  void loadFile(final String saveUrl, String path, String name){
        File file=new File(path,name);
        if (file!=null&&file.exists()){
            file.delete();
        }
        OkHttpUtils.get().url(saveUrl).build()
                .execute(new FileCallBack(path,name) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("legend", "onError: ");
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.i("legend", "onResponse: ");
                        if (saveUrl.contains("apk")){
                            apkFile= response;
                            Log.i("legend", "onResponse: "+response.getPath());
                            Log.i("legend", "onResponse: "+response.getAbsolutePath());
                            try {
                                Runtime.getRuntime().exec("chmod 777 "+response.getAbsolutePath());
                                handler.sendEmptyMessageDelayed(100,2000);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }
    private void editInfo(String key, String info){
        SharedPreferences.Editor editor = sharePreference.edit();
        editor.putString(key, info);
        editor.commit();
    }

    @Override
    public void onError(int code, String msg) {

    }

    @Override
    public void onHomePageCompleted(HomePagePresenter presenter, int count1, HomePageBean dto) {

    }

    @Override
    public void onNoticCompleted(HomePagePresenter presenter) {

    }
}
